<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<body>
<input type="text" id="input_text" placeholder="输入内容">
<div id="test">
    <a href="javascript:void(0)">点击发送</a>
</div>

<!--<textarea name="" id="" cols="30" rows="10" disabled></textarea>-->

<div>
    <ul id="content">
        <!--        <li>初始化</li>-->
    </ul>
</div>

</body>
</html>

<script>
    $('#test').click(function () {
        var a = $("#input_text").val();
        if ("WebSocket" in window) {
            console.log("您的浏览器支持websocket\n");
            var ws = new WebSocket("ws://127.0.0.1:2346");//创建websocket对象
            ws.onopen = function () {
                // ws.send("连接已建立\n");
                ws.send(a);
                console.log("数据发送中");
            }

            ws.onmessage = function (evt) {
                console.log(evt);
                var recv_msg = evt.data;
                // $("#content").append(recv_msg);
                var str = "<li>" + recv_msg + "</li>"
                $("#content").append(str);
                console.log("接受到的数据为:" + recv_msg);
            }

            ws.onerror = function (evt, e) {
                console.log("错误信息为" + e);
            }

            ws.onclose = function () {
                console.log("连接已关闭");
            }

        } else {
            console.log("您的浏览器不支持websocket\n");
        }
    });
</script>
